const jwt = require('jsonwebtoken');
const createUser = async ctx => {
	const { service, request } = ctx
	const res = await service.user.createUser(ctx, request.body)
	ctx.body = res.id
	ctx.msg = "添加用户成功"
}

const getUser = async ctx => {
	const { service, request } = ctx
	ctx.body = await service.user.getUser(ctx, request.query)
	ctx.msg = '查询成功'
}

const login = async ctx => {
	const { service, request } = ctx
	const { username, password } = request.body

	const res = await service.user.Login(username)
	if (res) {
		if (ctx.utils.md5(password) === res.password) {
			delete res.dataValues.password
			ctx.body = {
				userInfo: res,
				token: jwt.sign({
					username,
				}, 'biluo_koa', { expiresIn: '2h' })
			}
			ctx.msg = "登录成功"
		} else {
			ctx.msg = "密码错误"
		}
	} else {
		ctx.msg = "没有该用户"
	}
}

module.exports = {
	createUser,
	getUser,
	login
}
